import os
import time
import logging
from logging.handlers import RotatingFileHandler

class LevelFilter(logging.Filter):
    def __init__(self, level):
        super().__init__()
        self.level = level

    def filter(self, record):
        return record.levelno == self.level

class LogUtils:
    _instance = None
    _current_date = None
    _initialized = False  # 添加一个标志位来检查是否已经初始化

    def __new__(cls, base_log_path="logs"):
        current_date = time.strftime('%Y_%m_%d')
        if cls._instance is None or current_date != cls._current_date:
            cls._current_date = current_date
            cls._instance = super(LogUtils, cls).__new__(cls)
            cls._instance.__init__(base_log_path)
        return cls._instance

    def __init__(self, base_log_path="logs"):
        if self._initialized:
            return  # 如果已经初始化，则不再执行下面的代码
        timestamp = self._current_date + "_logs"
        self.logfile_path = os.path.join(base_log_path, timestamp)

        if not os.path.exists(self.logfile_path):
            os.makedirs(self.logfile_path)

        self.logger = logging.getLogger(__name__)
        self.logger.setLevel(logging.DEBUG)

        formatter = logging.Formatter('%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s')

        log_levels = {
            'INFO': 'info',
            'WARNING': 'warning',
            'ERROR': 'error',
            'CRITICAL': 'critical',
            'DEBUG': 'debug',
        }

        for level_name, file_prefix in log_levels.items():
            level = getattr(logging, level_name)
            log_file = os.path.join(self.logfile_path, f"{file_prefix}.log")
            handler = RotatingFileHandler(log_file, maxBytes=2*1024*1024, backupCount=5, encoding='utf-8')
            handler.setLevel(level)
            handler.setFormatter(formatter)
            handler.addFilter(LevelFilter(level))
            self.logger.addHandler(handler)

        # console = logging.StreamHandler()
        # console.setLevel(logging.INFO)
        # console.setFormatter(formatter)
        # self.logger.addHandler(console)

        print(f"日志目录已准备好：{self.logfile_path}")
        self._initialized = True  # 设置初始化标志位为True

    def get_log(self):
        return self.logger

# 使用示例
log_util = LogUtils()
logger = log_util.get_log()

    
